<template>
  <a-modal
    title="添加申报职位"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :label="formItem.label"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-for="formItem in formOptions"
          :key="formItem.label">
          <component
            :is="'a-' + formItem.type"
            v-bind="formItem.attrs"
            v-decorator="formItem.dec"></component>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import av from '../../api/av'

export default {
  data () {
    return {
      id: '',
      type: 'add',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      formOptions: [
        { label: '申报职位',
          type: 'input',
          dec: ['job', { rules: [
            { required: true, message: '请输入申报职位' }
          ] }] },
        { label: '说明',
          type: 'input',
          dec: ['mark', { rules: [
            { required: true, message: '请输入说明' }
          ] } ] },
        { label: '介绍',
          type: 'textarea',
          dec: ['introduction', { rules: [
            { required: true, message: '请输入介绍' }
          ] }],
          attrs: { rows: 3 } },
        { label: '是否展示',
          type: 'switch',
          dec: ['status', { valuePropName: 'checked', initialValue: true }]
        }
      ],
      visible: false,
      confirmLoading: false,

      form: this.$form.createForm(this)
    }
  },
  computed: {
    isAdd () {
      return this.type === 'add'
    }
  },
  methods: {
    add () {
      this.type = 'add'
      this.visible = true
    },
    handleSubmit () {
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.confirmLoading = true
          const text = this.isAdd ? '新增' : '编辑'
          const service = this.isAdd ? av.add('jobType', values) : av.update('jobType', values, this.id)
          service.then(res => {
            this.close()
            this.$message.success(text + '成功')
            this.$emit('ok', values)
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    close () {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
    },
    edit (record) {
      this.id = record.objectId
      this.type = 'edit'
      this.visible = true
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(record)
      })
    }
  }
}
</script>
